//
//  SCCarMaintenReportVC.m
//  Shuaiche
//
//  Created by liyanan on 2019/8/7.
//  Copyright © 2019 zzs. All rights reserved.
//  维保报告

#import "SCCarMaintenReportVC.h"
#import "SCMaintenCarView.h"
#import "SCCarMaintenTable.h"
#import <Masonry.h>
#import "SCHttpManager.h"
#import "NSString+Helper.h"
#import "SCMaintenanceModel.h"
#import <MJRefresh.h>
#import "SCWebViewController.h"
#import "SCTestReportUploadVC.h"
#import "SCBaseEmptyView.h"
#import "SCMaintenAlertTexttField.h"
#import "MBProgressHUD+Add.h"
#import "Config.h"
#import "NSString+SCStringHandle.h"
#import "SCVinScanViewController.h"
#import "SCRNEventManager.h"
//#import "SCRNRootViewController.h"
@interface SCCarMaintenReportVC ()<SCCarMaintenTableDelegate,SCBaseEmptyViewDelegate, UITextFieldDelegate>
@property (nonatomic, strong) SCMaintenCarView *carView;
@property (nonatomic, strong) SCCarMaintenTable *tableView;
@property (nonatomic, assign) NSInteger pageNo;
@property (nonatomic, assign) NSInteger pageSize;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) SCBaseEmptyView *emptyView;
@property (nonatomic, strong) SCMaintenAlertTexttField *alertView;

@end

@implementation SCCarMaintenReportVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"维保报告";
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(maintenEnableChanged) name:SCNOTIFICATION_MAINTEN_ENABLE object:nil];
  [self refreshView];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (self.alertView) {
        self.alertView.hidden = NO;
    }
}

- (void)refreshView {
  if ([NSString SC_isBlankString:self.vcode]) {
    [self.view addSubview:self.emptyView];
  } else {
    [self setUpSubviews];
    [self fetchCarInfo];
    self.pageSize = 4;
    [self loadData];
  }
}

//- (BOOL)navigationShouldPopOnBackButton {
//    if (!_carId) {
//        [self.preParam setValue:_vcode forKey:kVcode];
//        self.upload(self.preParam);
//    }
//    return YES;
//}
- (void)maintenEnableChanged {
    [self.tableView showFooterBtnAtIndex:2 isShow:[[NSUserDefaults standardUserDefaults] boolForKey:kMaintenEnable]];
}

-(NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}

#pragma mark -

- (void)loadMoreData {
    self.pageNo ++;
    [self loadData];
}
//获取 车辆维保记录
- (void)loadData {
    if ([NSString SC_isBlankString:_vcode]) {
        return;
    }
    WEAKSELF
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:@(self.pageNo) forKey:kPageNo];
    [dic setValue:_vcode forKey:kVcode];
    [dic setValue:@(_pageSize) forKey:kPageSize];
  
  [[SCHttpManager shareInstance] httpPost:@"/stockprod/maintenanceRecord/list" param:dic completion:^(id response, NSError *error){
    if (error) {
        
    }else {
      NSArray *lists = response[kResultList];
      if (weakSelf.pageNo == 1) {
          [weakSelf.dataSource removeAllObjects];
      }
      for (NSDictionary *dic in lists) {
          SCMaintenanceModel *model = [SCMaintenanceModel yy_modelWithDictionary:dic];
          [weakSelf.dataSource addObject:model];
      }
      NSNumber *totalSize = response[kTotalSize];
      weakSelf.tableView.footerHeight = weakSelf.dataSource.count ? 80 : 56;
      [weakSelf.tableView reloadTableView:weakSelf.dataSource totalCount:totalSize.integerValue updateConstraints:nil];
      if (lists.count < weakSelf.pageSize) {
          [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
          [weakSelf.tableView.mj_footer setHidden:YES];
          return ;
      }
    }
    [weakSelf.tableView.mj_footer endRefreshing];
    [weakSelf.tableView.mj_footer setHidden:NO];
  }];
}

//添加车辆vin码
- (void)inserVcodeByCarId: (NSString *)carId completion: (void(^)(void))completion {
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:carId forKey:kCarId];
    [dic setValue:_vcode forKey:kVcode];
    [dic setValue:[Config sharedConfig].user.fullname forKey:kOperator];
  [[SCHttpManager shareInstance] httpGet:@"/stockprod/car/insertVcodeByCarId" param:dic completion:^(id response, NSError *error){
    if (error) {
        
    }else {
      if (response) {
          if (self.upload) {
            self.upload(@{kVcode: self.vcode});
          }
      }
  }
  }];
}

//获取车辆信息
- (void)fetchCarInfo {
    self.carView.vcode = _vcode;
    NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithObject:_vcode forKey:@"vin"];
    WEAKSELF
  [[SCHttpManager shareInstance] httpGet:@"/baseprod/cartype/getCarCategoryByVin" param:dic completion:^(id response, NSError *error){
    if (error) {
        
    }else {
      NSArray *data = response;
      NSString *_logoPic = @"";
      NSString *carName = @"";
      for (int i=0; i<data.count; i++) {
          NSNumber *level = data[i][kLevel];
          if (level.intValue <= 5 && level.intValue%2==1) { //只需要拼接 1品牌 3车系 5车型
              NSString *name = data[i][kName];
              NSString *logo = data[i][kLogo];
              if (![NSString SC_isBlankString:name]) {
                  carName = [[carName stringByAppendingString:name] stringByAppendingString:@"-"];
              }
              if (![NSString SC_isBlankString:logo]) {
                  _logoPic = logo;
              }
          }
      }
      if (carName.length) {
          carName = [carName substringToIndex:carName.length-1];
      }
      weakSelf.carView.carName = carName;
      weakSelf.carView.brandLogo = _logoPic;
  }
  }];
}


#pragma mark-
#pragma mark- Subviews
- (void)setUpSubviews {
    [self.view addSubview:self.carView];
    [self.view addSubview:self.tableView];
    self.tableView.tableDelegate = self;
    self.tableView.showCount = 4;
    self.tableView.moreHeight = 40;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, kSCScreenBottomOffset, 0);
    [self.tableView showFooterViewWithBtnTitles:@[@"立即查询",@"手动上传"] btnHeight:46 footerHeight:56 configBtns:nil];
    [self maintenEnableChanged];

}
- (SCBaseEmptyView *)emptyView {
    if (!_emptyView) {
        _emptyView = [[SCBaseEmptyView alloc] initWithFrame:CGRectMake(0, 0, kSCScreenWidth, kSCScreenHeight) imageName:@"emp_group" msg:@"车辆暂无VIN码\n帅车内采无法为您匹配维保记录" showBottomBtn:YES btnTitle:@"点击上传VIN码"];
        _emptyView.delegate = self;
        
    }
    return _emptyView;
}

- (SCMaintenCarView *)carView {
    if (!_carView) {
        _carView = [[NSBundle mainBundle] loadNibNamed:@"SCMaintenCarView" owner:nil options: nil][0];
        _carView.frame = CGRectMake(0, 10, kSCScreenWidth, 120);
    }
    return _carView;
}
- (SCCarMaintenTable *)tableView {
    if (!_tableView) {
        _tableView = [[SCCarMaintenTable alloc] initWithFrame:CGRectMake(0, self.carView.frame.origin.y+120, kSCScreenWidth, kSCScreenHeight-kSCNavigationHeight-10-120) style:(UITableViewStylePlain)];
    }
    return _tableView;
}

#pragma mark- SCBaseEmptyViewDelegate
- (void)didClickBottomBtn {
    WEAKSELF
    __block SCMaintenAlertTexttField *alert = [[SCMaintenAlertTexttField alloc] initWithTitle:@"" message:@"车辆暂未添加车架号，请先在上方框内填写完整的VIN码" mainAct:@"确认" otherAct:@"取消" handleBlock:^(NSInteger index) {
        if (index == 0) { //确认
            if ([NSString SC_isBlankString:_vcode]) {
                [MBProgressHUD showPlainText:@"请输入VIN码" toView:alert];
                return;
            }
            if (_vcode.length != 17) {
                [MBProgressHUD showPlainText:@"请输入正确的VIN码" toView:alert];
                return;
            }else {
                if ([_vcode checkVin]) {
                    weakSelf.vcode = _vcode;
                    [self refreshView];
                    if (weakSelf.carId) {
                        [weakSelf inserVcodeByCarId:weakSelf.carId completion:nil];
                    }
                    [alert hideView];
                }else {
                    [MBProgressHUD showPlainText:@"请输入正确的VIN码" toView:alert];
                    return;
                }
            }
        }else {
            [alert hideView];
        }
    } textChanged:^(NSString * text) {
        _vcode = text;
    }];
    self.alertView = alert;
    [alert showWithView:self.view];
}
#pragma mark- SCCarMaintenTableDelegate
- (void)showMaintenanceDetailWithModel:(SCMaintenanceModel *)model isShowMore:(BOOL)isShowMore {
    if (isShowMore) {//展开数据，获取全部数据
        if (!self.tableView.mj_footer) {
            self.pageNo = 1;
            self.pageSize = 20;
            [self loadData];
            MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
            footer.stateLabel.textColor = SCColor(0x999999);
            [footer setTitle:@"" forState:MJRefreshStateNoMoreData];
            [footer setTitle:@"正在加载..." forState:MJRefreshStateRefreshing];
            self.tableView.mj_footer = footer;
        }
    }else if (model){//跳转维保详情
      SCWebViewController *webVC = [[SCWebViewController alloc] init];
        if (model.reportPdf.length>0) {
          webVC.urlPath = model.reportPdf;
        }else if (model.reportWapUrl && model.reportWapUrl.length>0) {
          webVC.urlPath = model.reportWapUrl;
        }else if (model.reportPics.count>0){
            webVC.urlPath = [NSString stringWithFormat:@"/maintenanceReport?maintenanceId=%@",model.maintenanceId];
        }
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (void)footerViewBtnClick:(NSInteger)btnIndex {
    if (btnIndex == 2) { //手动上传
        SCTestReportUploadVC *vc = [[SCTestReportUploadVC alloc] init];
        vc.vcode = _vcode;
        vc.carId = _carId;
        if (!_carId) { //发车/车辆编辑
            vc.upload = self.upload;
            vc.preParams = self.preParam;
        }else {
            WEAKSELF
            vc.upload = ^(NSDictionary * _Nonnull info) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    //刷新数据
                    weakSelf.pageNo = 1;
                    [weakSelf loadData];
                    if (weakSelf.upload) {
                        weakSelf.upload(nil);
                    }
                });
               
            };
        }
        [self.navigationController pushViewController:vc animated:YES];
    }else { //自己查
      [[SCRNEventManager shareInstance] foursQuery:@{@"vcode": self.vcode, @"page": self.page ? self.page:@""}];
      [self.navigationController popViewControllerAnimated:NO];
//        NSMutableDictionary *paramas = [NSMutableDictionary dictionaryWithCapacity:0];
//        paramas[@"vin"] = _vcode;
//        SCRNRootViewController *foursVC = [[SCRNRootViewController alloc] init];
//        foursVC.rnPageType = RNPageType_7;
//        foursVC.properties = paramas;
//        [self.navigationController pushViewController:foursVC animated:YES];
    }
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
